package com.husky.easyexcle.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.husky.easyexcle.annotation.ExportAppendStringAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * @Author husky
 * @Date 2022/3/16 16:36
 * @Description: 自定义导出时追加字符串转换器
 * 注意： 此注解不可以写在 BigDecimal 类型的属性上
 **/
@Slf4j
public class CustomExportAppendStringConverter implements Converter<String> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
    /**
     * 这里是读的时候会调用
     *
     * @return
     */
    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return cellData.getStringValue();
    }


    /**
     * 这里是写的时候会调用
     * @return
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {

        String result = "";
        try{
            ExportAppendStringAnnotation annotation = context.getContentProperty().getField().getAnnotation(ExportAppendStringAnnotation.class);
            if(annotation != null){
                //获取带写入Excel中数据 并且将格式强转为字符串
                // String value = context.getValue();
                String value = context.getValue()+"";

                //获取的String类型数据不为空
                if(StringUtils.hasLength(value)){
                    result = value;
                    // 如果开始位置追加内容不为空
                    if(!ObjectUtils.isEmpty(annotation.beginPositionContent())){
                        result = annotation.beginPositionContent()+result;
                    }

                    // 如果结束位置追加内容不为空
                    if(!ObjectUtils.isEmpty(annotation.endPositionContent())){
                        result = result+annotation.endPositionContent();
                    }
                }
            }else{
                log.error("导出时追加指定字符串，缺少配套注解@ExportAppendStringAnnotation");
            }
        }catch (Exception e){
            log.error("自定义导出时追加字符串转换器，获取属性反射异常。Exception={}",e);
        }
        return new WriteCellData<>(result);
    }
}
